#include <iostream>
#include <utility> // for std::move
#include <string.h>

class String {
    char* data;
    size_t length;
    
public:
    // 构造函数
    String(const char* str = "") {
        length = strlen(str);
        data = new char[length + 1];
        strcpy(data, str);
        std::cout << "Constructed: " << data << std::endl;
    }
    
    // 拷贝构造函数
    String(const String& other) {
        std::cout << "String(const String& other) ..." << std::endl;
        length = other.length;
        data = new char[length + 1];
        strcpy(data, other.data);
        std::cout << "Copied: " << data << std::endl;
    }
    
    // 移动构造函数
    String(String&& other) noexcept {
        std::cout << " move String(const String&& other) ..." << std::endl;
        data = other.data;    // 窃取资源
        length = other.length;
        other.data = nullptr; // 置空原对象
        other.length = 0;
        std::cout << "Moved: " << data << std::endl;
    }
    
    // 析构函数
    ~String() {
        if (data) {
            std::cout << "Destructing: " << data << std::endl;
            delete[] data;
        }
    }
    
    // 移动赋值运算符
    String& operator=(String&& other) noexcept {
        std::cout << " String& operator=(String&& other)..." << std::endl;

        if (this != &other) {
            delete[] data;      // 释放现有资源
            data = other.data;  // 窃取资源
            length = other.length;
            other.data = nullptr;
            other.length = 0;
            std::cout << "Move assigned: " << data << std::endl;
        }
        return *this;
    }
};

int main() {
    String s1("Hello");      // 普通构造
    String s2(s1);           // 拷贝构造
    String s3(std::move(s1));// 移动构造
    
    String s4("World");
    s4 = std::move(s2);      // 移动赋值
    
    return 0;
}